import React, {Component,} from 'react'
import Admin from "../../../layout/Admin";
import TopicModel from "../../../model/topic";
import {
    Button,
    message,
    PageHeader,
    Popconfirm,
    Table,
    Pagination,
    Modal,
    Form,
    Input,
    Upload,
    Checkbox,
    InputNumber
} from "antd";
import {LeftOutlined, RightOutlined, UploadOutlined,} from '@ant-design/icons';
import {Radio,} from "antd";
import Info from "../../../service/info";

class Topic extends Component {

    constructor(props) {
        super(props)
        this.model = new TopicModel()
        this.state = {
            p: 0,
            list: [],
            form: {
                title: '',
                txt: '',
                lock: false,
            },

            officialComment: '',

            limit: {
                pushlv: 0,
                commentlv: 0,
                zanlv: 0,
            },
            type: 'time',

            imgs: [],
            modal: {
                add: false,
                limit: false,
                officialComment: false,
            }
        }
    }

    componentDidMount() {
        this.all()
        this.getLimit()
    }

    modalShow = (key) => {
        this.setState({
            modal: {
                [key]: true
            },
        })
    }

    modalCancel = (key) => {
        this.setState({
            modal:{
                [key]: false,
            }
        })
    }

    all = () => {
        const p = this.state.p
        this.fetchPage(p)
    }

    add = (params) => {
        const m = this.model
        params.uid = 'fangguan'
        // params.imgs = JSON.stringify('[]')
        params.imgList = this.state.imgs
        return m.add(params)
    }

    ding = (record) => {
        const m = this.model
        const id = record.Id
        // const state = 1
        const state = record.Ding === 0 ? 1 : 0
        m.ding({id, state,})
            .then(resp => {
                if (resp.data.ok === 1) {
                    Info.success('成功')
                }
                this.all()
            })
    }

    delete = (record) => {
        const m = this.model
        const id = record.Id
        m.delete({id,})
            .then(resp => {
                if (resp.data.ok === 1) {
                    message.success('删除成功')
                }
            })
            .then(() => {
                this.all()
            })
    }

    officialComment = () => {
        this.model
            .officialComment({Txt: this.state.officialComment, HuaTiId: this.state.curTopic.Id,})
            .then(resp => {
                if (resp.data.ok === 1) {
                    Info.success('回复成功')
                    this.setState({
                        officialComment: '',
                    }, () => {
                        this.modalCancel('officialComment')
                    })
                }
            })
    }

    addJH = (record, isJH,) => {
        const m = this.model
        const id = record.Id
        const state = isJH ? 0 : 1
        m.addJH({id, state,})
            .then(resp => {
                if (resp.data.ok === 1) {
                    message.success(isJH ? '取消加精成功' : '加精成功')
                }
            })
            .then(() => {
                this.all()
            })
        console.log(record)
    }

    getLimit = () => {
        this.model
            .getLvLimit()
            .then((resp) => {
                // pushlv 话题发表等级限制
                // commentlv 评论等级限制
                // zanlv 赞等级限制
                const {
                    pushlv,
                    commentlv,
                    zanlv,
                } = resp.data.ok
                this.setState({
                    limit: {
                        pushlv,
                        commentlv,
                        zanlv,
                    }
                })
            })
    }

    setLimit = (params) => {
        this.model
            .setLvLimit(params)
            .then(resp => {
                if (resp.data.ok === 1) {
                    Info.success('修改成功')
                }
            })
            .then(() => this.getLimit())
    }

    emptyAddForm = () => {
        this.form.resetFields()
    }

    onAddFinish = (params) => {
        // this.add(params)
        //     .then(resp => {
        //         console.log(resp)
        //     })
        this.add(params)
            .then((resp) => {
                if (resp.data.ok === 1) {
                    Info.success('发帖成功')
                    return true
                }
                if (resp.data.err) {
                    Info.error(resp.data.data)
                    return false
                }
            })
            .then(result => {
                if (result) {
                    this.emptyAddForm()
                    this.modalCancel('add')
                    this.all()
                }
            })
            .catch(e => {
                Info.error('有错')
            })
    }

    onLimitFinish = (params) => {
        console.log(params)
        this.setLimit(params)
    }

    fetchPage = (p) => {
        const m = this.model
        const type = this.state.type
        let params = {p, [type]: 1,}
        m.all(params)
            .then(resp => {
                const list = resp.data.ok
                // console.log(data)
                this.setState({
                    list,
                })
            })
    }

    prevPage = () => {
        const p = this.state.p - 1
        this.setState({
            p,
        }, () => {
            this.fetchPage(p)
        })
    }

    nextPage = () => {
        const p = this.state.p + 1
        this.setState({
            p,
        },() => {
            this.fetchPage(p)
        })
    }

    onRatioChange = (e) => {
        const v = e.target.value
        const stateType = this.state.type
        if (stateType === v) return
        this.setState({
            p: 0,
            type: v,
        }, () => {
            this.all()
        })
    }

    uploadInputProps = (name) => {

        const fileList = this.state[name]

        return {

            onRemove: file => {
                this.setState(state => {
                    const index = state[name].indexOf(file);
                    const newFileList = state[name].slice();
                    newFileList.splice(index, 1);
                    return {
                        [name]: newFileList,
                    }
                })
            },

            beforeUpload: file => {
                this.setState(state => ({
                    [name]: [...state[name], file],
                }))
                return false
            },

            fileList,
        }

    }

    render() {

        const header = <div style={{background: '#fff'}}>
            <PageHeader title='话题'/>
        </div>

        // Id: 18
        // Uid: "d3dc0be2-2e33-4cea-8a71-f7a24818d66f"
        // Username: "18859900526"
        // Avatar: "http://test.youtoball.com/avatar/d3dc0be2-2e33-4cea-8a71-f7a24818d66f.jpg"
        // Lv: 12
        // Title: "title"
        // Txt: "txt"
        // Img: "["http://test.youtoball.com/huati/20200403111325.1.jpg","http://test.youtoball.com/huati/20200403111325.2.png"]"
        //     Comment: 0
        // Jing: 0
        // Createt: 1585883605
        // Commentt: 0

        const columns = [
            {
                title: 'Id',
                dataIndex: 'Id',
                render: text => <span>{text}</span>,
            },
            {
                title: '用户名',
                dataIndex: 'Username',
                render: text => <span>{text}</span>,
            },
            {
                title: '标题',
                dataIndex: 'Title',
                render: text => <span>{text}</span>,
            },
            {
                title: '精华',
                dataIndex: 'Jing',
                render: text => <span>{text > 0 ? '精' : '普通'}</span>,
            },
            // {
            //     title: '创建时间',
            //     dataIndex: 't',
            //     // render: text => <span>{this.formatTime(new Date(text * 1000))}</span>,
            // },
            {
                title: '操作',
                dataIndex: '操作',
                render: (text, record) => {

                    const JHState = record.Jing
                    const isJH = JHState > 0

                    return <div>

                        <a style={{marginRight: 8,}}>
                            <Popconfirm
                                title={isJH ? "确定取消加精?" : "确定加精?"}
                                onConfirm={(e) => this.addJH(record, isJH)}
                            >
                                <span>{isJH ? "取消加精" : "加精"}</span>
                            </Popconfirm >
                        </a>

                        <a style={{marginRight: 8,}} onClick={() => {
                            this.setState({
                                curTopic: record,
                            })
                            console.log(record)
                            this.modalShow('officialComment')
                        }}>
                            <span>房管评论</span>
                        </a>

                        <a style={{marginRight: 8,}}>
                            <Popconfirm
                                title={'顶'}
                                onConfirm={() => this.ding(record)}
                            >
                                {record.Ding === 0 ? <span>顶</span> : <span>取消置顶</span>}
                            </Popconfirm>
                        </a>

                        <a>
                            <Popconfirm
                                title="确定删除?"
                                onConfirm={(e) => this.delete(record)}
                            >
                                <span>删除</span>
                            </Popconfirm >
                        </a>

                    </div>

                },
            },

        ]

        const footer = <div style={{
            paddingTop: 8,
            display: "flex",
            justifyContent: "flex-end",
        }}>
            <Button
                style={{marginRight: 8,}}
                onClick={(e) => this.prevPage()}
            ><LeftOutlined /></Button>
            <a className='ant-pagination-item ant-pagination-item-active '>{this.state.p + 1}</a>
            <Button
                onClick={(e) => this.nextPage()}
            ><RightOutlined /></Button>
        </div>

        const table = <div className='list-container'>

            <div style={{marginBottom: '16px',}}>
                <Button onClick={() => this.modalShow('add')}>
                    房管发帖
                </Button>
                <Button onClick={() => this.modalShow('limit')}>
                    互动限制
                </Button>
            </div>


            <div style={{marginBottom: '16px',}}>
                <Radio.Group onChange={this.onRatioChange} value={this.state.type}>
                    <Radio value={'time'}>按时间</Radio>
                    <Radio value={'ding'}>顶</Radio>
                    <Radio value={'jing'}>加精</Radio>
                    <Radio value={'fangguan'}>房管</Radio>
                    <Radio value={'comment'}>最新评论</Radio>
                </Radio.Group>
            </div>

            <Table
                dataSource={this.state.list}
                columns={columns}
                rowKey={(record, index) => index}
                pagination={false}
            />

            {footer}

        </div>

        const layout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        }

        const addForm = <Form
            {...layout}
            ref={el => this.form = el}
            initialValues={this.state.form}
            onFinish={this.onAddFinish}
        >
            <Form.Item
                label="标题"
                name="title"
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="内容"
                name="txt"
            >
                <Input.TextArea />
            </Form.Item>

            <Form.Item
                label="帖子图片"
                help="上传图片大小不可超过1m"
            >
                <Upload
                    {...this.uploadInputProps('imgs')}
                    multiple={true}
                >
                    <Button>
                        <UploadOutlined  /> Click to upload
                    </Button>
                </Upload>
            </Form.Item>

            <Form.Item
                name="lock"
                valuePropName="checked"
                label='锁帖'
            >
                <Checkbox />
            </Form.Item>

            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>

                <Button onClick={() => this.modalCancel('add')}  style={{marginRight: '8px',}}>
                    取消
                </Button>

                <Button type="primary" htmlType="submit">
                    添加
                </Button>

            </Form.Item>
        </Form>

        // pushlv 话题发表等级限制
        // commentlv 评论等级限制
        // zanlv 赞等级限制
        const limitForm = <Form
            {...layout}
            ref={el => this.form = el}
            initialValues={this.state.limit}
            onFinish={this.onLimitFinish}
        >
            <Form.Item
                label="话题发表等级限制"
                name="pushlv"
            >
                <InputNumber />
            </Form.Item>

            <Form.Item
                label="评论等级限制"
                name="commentlv"
            >
                <InputNumber />
            </Form.Item>

            <Form.Item
                label="赞等级限制"
                name="zanlv"
            >
                <InputNumber />
            </Form.Item>

            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>

                <Button onClick={() => this.modalCancel('limit')}  style={{marginRight: '8px',}}>
                    取消
                </Button>

                <Button type="primary" htmlType="submit">
                    添加
                </Button>

            </Form.Item>
        </Form>

        const addModal = <Modal
            title='房管发帖'
            visible={this.state.modal.add}
            footer={null}
            maskClosable={true}
            onCancel={() => this.modalCancel('add')}
        >
            {addForm}
        </Modal>

        const limitModal = <Modal
            title='设置互动限制'
            visible={this.state.modal.limit}
            footer={null}
            maskClosable={true}
            onCancel={() => this.modalCancel('limit')}
        >
            {limitForm}
        </Modal>

        const officialCommentModal = <Modal
            title='房管回帖'
            visible={this.state.modal.officialComment}
            footer={null}
            maskClosable={true}
            onCancel={() => {
                this.modalCancel('officialComment')
                this.setState({
                    officialComment: '',
                })
            }}
        >
            <Input.TextArea
                value={this.state.officialComment}
                onChange={(e) => this.setState({officialComment: e.target.value,})}
            />
            <Button
                onClick={() => this.officialComment()}
            >确认回复</Button>
        </Modal>

        return <>
            {addModal}
            {limitModal}
            {officialCommentModal}
            <Admin>
                {header}
                {table}
            </Admin>
        </>
    }
}

export default Topic
